<?php

class Tourism_goods_image_model extends CI_Model
{
    private $table = 'tourism_goods_image';

    /*
     * 根据商品获取多图
     * */
    public function findByGoodId($params)
    {
        if (isset($params['is_main'])) {
            $this->db->where('is_main', $params['is_main']);
        }
        $this->db->where('goods_id', $params['goods_id']);
        return $this->db->get($this->table);
    }

    /*
     * 插入图片
     * */
    public function insertImage($goods_id, $imageData)
    {

        $this->db->where('goods_id', $goods_id);
        $result = $this->db->get($this->table);
        $data = array(
            'goods_id' => $goods_id,
            'images' => trim($imageData['file_name']),
        );
        if ($result->num_rows() == 0) {
            $data['is_main'] = 1;
        }

        $this->db->insert($this->table, $data);
        return $this->db->insert_id();
    }

    /*
     * 插入图片
     * */
    public function insertImageLine($goods_id, $imageData)
    {
        $data = array(
            'goods_id' => $goods_id,
            'images' => trim($imageData['file_name']),
        );
        $this->db->insert($this->table, $data);
        return $this->db->insert_id();
    }

    /*
    * 设置默认
    * */
    public function mainImage($id, $goods_id)
    {
        $this->db->where('goods_id', $goods_id);
        $this->db->update($this->table, array('is_main' => 0));
        $this->db->where('id', $id);
        return $this->db->update($this->table, array('is_main' => 1));
    }

    /*
     * 删除图片
     * */
    public function deleteImage($id)
    {
        $this->db->where('id', $id);
        return $this->db->delete($this->table);
    }

    /*
     * 删除图片
     * */
    public function getImageById($id)
    {
        $this->db->where('id', $id);
        return $this->db->get($this->table)->row();
    }
    
    /**
     * @descripte   批量插入图片
     * @Author xiumao
     * @date 2016/6/15 0015 下午 5:34
     */
    public function insertImageBatch($goods_id, $imageData)
    {
        $this->db->where('goods_id', $goods_id);
        $result = $this->db->get($this->table);
        foreach ( $imageData as $key=>$val) {
            $insertArray[$key]['goods_id']  = $goods_id;
            $insertArray[$key]['images']  = $val;
            if ($result->num_rows() <= 0) {
                $insertArray[$key]['is_main'] = ( $key == 0 ) ? 1 : 0;
            }else{
                $insertArray[$key]['is_main'] = 0;
            }
        }

        return $this->db->insert_batch($this->table, $insertArray);
    }

}